package com.atguigu.day07;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

import java.util.HashMap;

public class Flink12_KeyedState_ReducingState {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2.从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);

        //3.使用process代替map，将数据转为WaterSensor
        SingleOutputStreamOperator<WaterSensor> waterSensorStream = streamSource.process(new ProcessFunction<String, WaterSensor>() {
            /**
             *
             * @param value 传入的数据
             * @param ctx 上下文对象
             * @param out 采集器
             * @throws Exception
             */
            @Override
            public void processElement(String value, Context ctx, Collector<WaterSensor> out) throws Exception {
                String[] split = value.split(",");
                out.collect(new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2])));
            }
        });

        //4.将相同id的数据聚合到一块
        KeyedStream<WaterSensor, Tuple> keyedStream = waterSensorStream.keyBy("id");

        //5.对VC求和  =>TODO 用键控状态ReducingState实现
        keyedStream.process(new KeyedProcessFunction<Tuple, WaterSensor, String>() {


            //定义一个累加器
//            private Integer vcSum = 0;
//            private HashMap<String, Integer> vcSumMap = new HashMap<>();

            //TODO 定义一个状态
            private ReducingState<Integer> reducingState;

            @Override
            public void open(Configuration parameters) throws Exception {
                //TODO 初始化状态
                reducingState = getRuntimeContext().getReducingState(new ReducingStateDescriptor<Integer>("vcSum", new ReduceFunction<Integer>() {
                    @Override
                    public Integer reduce(Integer value1, Integer value2) throws Exception {
                        return value1 + value2;
                    }
                }, Integer.class));
            }

            @Override
            public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {

                /*//1.判断集合中是否有相同id的数据，
                if (vcSumMap.containsKey(value.getId())){
                    //如果有的话取出原来的值累加并更新
                    Integer lastVcSum = vcSumMap.get(value.getId());
                    lastVcSum += value.getVc();
                    vcSumMap.put(value.getId(), lastVcSum);
                }else {
                    //如果不存在就将当前的vc写入
                    vcSumMap.put(value.getId(), value.getVc());
                }
*/

                //TODO 1.将数据存到状态中自动作累加计算
                reducingState.add(value.getVc());
                //TODO 取出状态中的结果并发送至下游
                out.collect(ctx.getCurrentKey()+":"+reducingState.get());
//                out.collect(value.getId()+":"+vcSumMap.get(value.getId()));
            }
        }).print();

        env.execute();

    }
}
